package com.googlecode.allinclusive.fw.core.server;

import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/*
 * 
 * <bean id="***Server" class="com.googlecode.allinclusive.fw.core.server.Server">
 * 		<property="processor" ref="***Processor"/>
 *      <property="interval" value="60000"/>
 *      <property="delay" value="0"/>      
 * </bean>
 */
public class Server {

	/** log实例*/
	private static final Log log = LogFactory.getLog(Server.class);
	
	/**
	 * 间隔时间
	 */
	private long interval = 60000l;
	
	/**
	 * 延时启动时间 
	 */
	private long delay = 0l;
	
	/**
	 * 定时器
	 */
	private Timer timer;
	
	/**
	 * 处理器
	 */
	private Processor processor;
	
	/**
	 * Start Server.
	 */
	@PostConstruct
	public void init() {
		log.info(this.getClass().getSimpleName() + " start...");
		TimerTask t = new TimerTask() {
			public void run() {
				try {
					// process
					processor.process();
				} catch (Throwable th) {
					// ignore
					log.warn(th.getMessage(), th);
				}
			}
		};
		
		timer = new Timer();
		timer.schedule(t, delay, interval);
	}
	
	/**
	 * Stop Server.
	 */
	@PreDestroy
	public void destroy() {
		log.info(this.getClass().getSimpleName() + " stop...");
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
	}
	
	/**
	 * 设置间隔时间
	 * @param interval 间隔时间
	 */
	public void setInterval(long interval) {
		this.interval = interval;
	}
	
	/**
	 * 设置延时时间
	 * @param delay 延时时间
	 */
	public void setDelay(long delay) {
		this.delay = delay;
	}
	
	/**
	 * 设置处理器
	 * @param processor 处理器
	 */
	public void setProcessor(Processor processor) {
		this.processor = processor;
	}
}
